package com.liu.frame.customview;

import android.content.Context;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.liu.frame.R;
import com.liu.frame.base.BaseActivity;
import com.liu.frame.base.BaseRecyclerViewAdapter;
import com.liu.frame.base.BaseViewHolder;
import com.liu.frame.utils.LogUtils;
import com.liu.frame.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created by 刘智强 on 2017/2/15.
 * 可以刷新的recyclerview
 */

public class PullTorefreshView<T> extends RelativeLayout implements BaseRecyclerViewAdapter.OnItemClickListner {
    private Context context;//上下文
    private BaseRecyclerViewAdapter<T> adapter;//适配器
    private List<T> datas = new ArrayList<>();//所有的数据
    private boolean isLoadMore;//是否能够加载更多
    private RelativeLayout layout_background;//父布局
    private PtrClassicFrameLayout ptrClassicFrameLayout;//刷新的控件
    private RecyclerView recyclerView;//列表控件

    private PullToRefrehListtener pullToRefrehListtener;//回调监听
    private LinearLayout layout_nodata;//无数据的布局
    private Button btn_retry_load_more;//重新加载
    /**
     * 刷新和加载模式
     */
    public static final int BOTH = 0;//刷新和加载都可以
    public static final int NONE = 1;//既不能刷新也不能加载
    public static final int REFRESH = 2;//只能刷新
    public static final int LOAD_MORE = 3;//只能加载更多


    /**
     * recycler的布局模式
     */
    public static final int vertical_LAYOUTMANAGER = 0;//竖直
    public static final int HORIZONTAL_LAYOUTMANAGER = 1;//水平
    public static final int GridLayoutManager = 2;//网格
    /**
     * 分页
     */
    public static final int page = 1;//页码
    public static final int epage = 15;//每一页的数据

    public boolean isRefresh = true;//来判断是加载还是刷新,true-刷新,false-加载
    public boolean isNeedShade = false;//是否需要遮罩 true-需要遮罩,false-不需要遮罩

    private int index = 0;//页码

    public boolean isNeedShade() {
        return isNeedShade;
    }

    public void setNeedShade(boolean needShade) {
        isNeedShade = needShade;
    }

    public static int getEpage() {
        return epage;
    }

    public PullToRefrehListtener getPullToRefrehListtener() {
        return pullToRefrehListtener;
    }


    public void setPullToRefrehListtener(PullToRefrehListtener pullToRefrehListtener) {
        this.pullToRefrehListtener = pullToRefrehListtener;
    }

    public PullTorefreshView(Context context) {
        super(context);
        this.context = context;
        initView(context);
    }


    public PullTorefreshView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initView(context);

    }

    public PullTorefreshView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        initView(context);

    }

    /**
     * 初始化view和监听
     */

    public void initView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.pull_to_refresh_view, this);
        ptrClassicFrameLayout = (PtrClassicFrameLayout) findViewById(R.id.ptr_framelayout);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        layout_nodata = (LinearLayout) findViewById(R.id.layout_nodata);
        btn_retry_load_more = (Button) findViewById(R.id.btn_retry_load_more);
        /**
         * 给按钮设置重新加载的监听
         */
        btn_retry_load_more.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                pullToRefrehListtener.retryLoadData();
            }
        });
        ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {

                pullToRefrehListtener.loadMore(page + index);
                isRefresh = false;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pullToRefrehListtener.refresh();
                isRefresh = true;
            }
        });

        /**
         * 判断滑动到底部就加载
         */

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }


            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //得到当前显示的最后一个item的view
                View lastChildView = recyclerView.getLayoutManager().getChildAt(recyclerView.getLayoutManager().getChildCount() - 1);
                //得到lastChildView的bottom坐标值
                int lastChildBottom = lastChildView.getBottom();
                //得到Recyclerview的底部坐标减去底部padding值，也就是显示内容最底部的坐标
                int recyclerBottom = recyclerView.getBottom() - recyclerView.getPaddingBottom();
                //通过这个lastChildView得到这个view当前的position值
                int lastPosition = recyclerView.getLayoutManager().getPosition(lastChildView);
                //判断lastChildView的bottom值跟recyclerBottom
                //判断lastPosition是不是最后一个position
                //如果两个条件都满足则说明是真正的滑动到了底部
                if (lastChildBottom == recyclerBottom && lastPosition == recyclerView.getLayoutManager().getItemCount() - 1) {
                    pullToRefrehListtener.loadMore(page + index);
                    isRefresh = false;
                }
            }
        });


    }

    /**
     * 初始化数据
     *
     * @param adapter
     * @param data
     */

    public void setData(final BaseRecyclerViewAdapter adapter, final List<T> data) {
        /**
         * 通过判断是否需要遮罩
         */
        if (data != null && data.size() <= epage && isNeedShade && isRefresh) {
            layout_nodata.setVisibility(VISIBLE);
        } else {
            layout_nodata.setVisibility(GONE);
        }
        /**
         * 通过判断是否需要加载更多
         */

        if (data != null && data.size() >= epage) {
            ptrClassicFrameLayout.setMode(PtrFrameLayout.Mode.BOTH);//可以加载和刷新
        } else {
            ptrClassicFrameLayout.setMode(PtrFrameLayout.Mode.REFRESH);//只能刷新
        }
        /**
         * 设置适配器
         */

        if (adapter != null && recyclerView.getAdapter() == null) {
            recyclerView.setAdapter(adapter);
        }
        adapter.setOnItemClickListner(this);

/**
 * 刷新和加载的不同处理
 */
        if (isRefresh) {
            //刷新
            index = 1;
            if (data.isEmpty()) {
                layout_nodata.setVisibility(View.VISIBLE);
            } else {
                layout_nodata.setVisibility(View.GONE);
            }
            adapter.refreshDatas(data);
        } else {
            index++;
            //加载
            if (!data.isEmpty()) {
                ToastUtils.myToast(context, "加载完成!");
                LogUtils.e("加载完成");
            }
            adapter.addDatas(data);
        }


    }

    /**
     * 设置分割线
     *
     * @param dividerItemDecoration
     */

    public void setItemDecoration(DividerItemDecoration dividerItemDecoration) {
        if (dividerItemDecoration != null) {
            recyclerView.addItemDecoration(dividerItemDecoration);
        }

    }

    /**
     * 设置刷新和加载模式
     *
     * @param mode
     */

    public void setFreshMode(int mode) {

        switch (mode) {

            case 0:
                ptrClassicFrameLayout.setMode(PtrFrameLayout.Mode.BOTH);
                break;
            case 1:
                ptrClassicFrameLayout.setMode(PtrFrameLayout.Mode.NONE);
                break;
            case 2:
                ptrClassicFrameLayout.setMode(PtrFrameLayout.Mode.REFRESH);
                break;
            case 3:
                ptrClassicFrameLayout.setMode(PtrFrameLayout.Mode.LOAD_MORE);
                break;
            default:
                ptrClassicFrameLayout.setMode(PtrFrameLayout.Mode.NONE);

        }


    }


    /**
     * 设置自定义刷新头部
     *
     * @param header
     */
    public void setHeaderView(MyPtrFrameLayoutHeader header) {
        if (ptrClassicFrameLayout != null) {
            ptrClassicFrameLayout.setHeaderView(header);
            ptrClassicFrameLayout.addPtrUIHandler(header);
        }
    }

    /**
     * 设置自定义加载footer
     *
     * @param footer
     */

    public void setFooterView(MyPtrFrameLayoutFooter footer) {
        if (ptrClassicFrameLayout != null) {
            ptrClassicFrameLayout.setHeaderView(footer);
            ptrClassicFrameLayout.addPtrUIHandler(footer);
        }
    }

    @Override
    public void onInvestNowClickListner(View v, int position) {

    }

    @Override
    public void onItemClickListner(View v, int position) {
        pullToRefrehListtener.onItemClickListener(v, position);

    }


    /**
     * 刷新和加载的回调接口
     *
     * @return
     */
    public interface PullToRefrehListtener {
        void refresh();

        void loadMore(int page);

        void retryLoadData();

        void onItemClickListener(View v, int position);

    }


    /**
     * 刷新和加载完成
     */

    public void refreshComplete() {
        ptrClassicFrameLayout.refreshComplete();

    }


    /**
     * 设置遮罩的view是否显示
     *
     * @param visibile
     */

    public void setEmptyViewVisibile(int visibile) {
        if (visibile == View.GONE) {
            layout_nodata.setVisibility(View.GONE);

        } else if (visibile == VISIBLE) {
            layout_nodata.setVisibility(View.VISIBLE);
        } else if (visibile == INVISIBLE) {
            layout_nodata.setVisibility(View.INVISIBLE);
        }

    }

    public void setLayoutManager(int type, int row) {
        switch (type) {
            case 0:
                recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));//不反转
                break;
            case 1:
                recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));//不反转
                break;
            case 2:
                recyclerView.setLayoutManager(new GridLayoutManager(context, row));
                break;
            default:
        }
    }


}
